package org.example.minebackend.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Delete;
import org.example.minebackend.mapper.HealthClubMapper;
import org.example.minebackend.mapper.PersonCenterMapper;
import org.example.minebackend.pojo.*;
import org.example.minebackend.pojo.dto.InvitationCollectPageDTO;
import org.example.minebackend.pojo.dto.InvitationDTO;
import org.example.minebackend.pojo.dto.PersonDTO;
import org.example.minebackend.service.HealthClubService;
import org.example.minebackend.service.PersonCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PersonCenterServiceImpl implements PersonCenterService {
    @Autowired
    PersonCenterMapper personCenterMapper;
    @Autowired
    private HealthClubMapper healthClubMapper;

    public List<RecipeEntry> getRecipeEntry(Integer userId) {
        List<RecipeEntry> recipeEntryList = new ArrayList<RecipeEntry>();
        // 查询该用户收藏的全部菜谱
        List<Integer> recipeId = personCenterMapper.getCollectionRecipeIdByUserId(userId);
        List<Recipe> recipes = personCenterMapper.getRecipeById(recipeId);
        for ( Recipe recipe : recipes ) {
            Integer id = recipe.getId();
            List<IngredientOfRecipe> ingredients = healthClubMapper.getIngredientsByRecipeId(id);
            RecipeEntry recipeEntry = HealthClubServiceImpl.getEntryByRecipeAndIngredients(recipe, ingredients);
            recipeEntryList.add(recipeEntry);
        }
        return recipeEntryList;
    }

    public User getMessage(Integer id) {
        User user = personCenterMapper.getMessage(id);
        return user;
    }

    public int updatePersonMessage(PersonDTO personDTO) {
        User user = personCenterMapper.getMessage(personDTO.getId());
        // 判断是否需要修改newUserName
        if(!(personDTO.getNewUserName() == null || personDTO.getNewUserName().isEmpty())) {
            user.setUsername(personDTO.getNewUserName());
        }
        // 判断是否需要修改image
        if(!(personDTO.getImage() == null || personDTO.getImage().isEmpty())) {
            user.setImage(personDTO.getImage());
        }
        // 判断是否需要修改密码
        // 如果不能，将密码newPassword置为null或者为""，在再调用方法。
        int status = 0;
        if(user.getPassword().equals(personDTO.getOldPassword()) && personDTO.getNewPassword() != null && !personDTO.getNewPassword().isEmpty()) {
            user.setPassword(personDTO.getNewPassword());
            personCenterMapper.updatePerson(user);
        } else {
            status = -1;
            if(personDTO.getNewPassword() == null || personDTO.getNewPassword().isEmpty()) {
                status = 0;
            }
            personCenterMapper.updatePerson(user);
        }
        return status;
    }

    public PageBean getInvitationEntry(InvitationCollectPageDTO invitationCollectPageDTO) {
        Integer page = invitationCollectPageDTO.getPage();  // 当前页
        Integer pageSize = invitationCollectPageDTO.getPageSize(); // 每页大小
        Integer userId = invitationCollectPageDTO.getUserId();

        List<Integer> invitationId = personCenterMapper.getCollectionInvitationByUserId(userId);
        // 启动分页（使用PageHelper进行分页）
        PageHelper.startPage(page, pageSize);

        // 查询该用户收藏的全部帖子
        List<Invitation> invitationList = personCenterMapper.getInvitationsById(invitationId);

        // 查找每个帖子的作者姓名并转化为DTO
        List<InvitationDTO> invitationDTOList = new ArrayList<>();
        for (Invitation invitation : invitationList) {
            User user = personCenterMapper.getMessage(invitation.getWriterId());
            InvitationDTO invitationDTO = new InvitationDTO(invitation, user.getUsername());
            invitationDTOList.add(invitationDTO);
        }

        // 使用PageHelper返回的Page对象
        Page<Invitation> invitationsPage = (Page<Invitation>) invitationList; // 这里应该获取 Page<Invitation> 对象

        // 创建一个新的 Page<InvitationDTO> 对象，并传入转换后的列表及分页信息
        Page<InvitationDTO> resultPage = new Page<InvitationDTO>(page, pageSize);
        resultPage.addAll(invitationDTOList);
        resultPage.setTotal(invitationsPage.getTotal()); // 设置总记录数

        // 创建 PageBean 返回结果
        PageBean pageBean = new PageBean((int) resultPage.getTotal(), resultPage);
        return pageBean;
    }
    public List<InvitationDTO> getInvitationEntryByUserId(Integer userId) {
        List<InvitationDTO> invitationDTOList = new ArrayList<>();
        // 查询该用户写过的全部帖子
        List<Invitation> invitationList = personCenterMapper.getInvitationsByUserId(userId);

        for (Invitation invitation : invitationList) {
            User user = personCenterMapper.getMessage(invitation.getWriterId());
            InvitationDTO invitationDTO = new InvitationDTO(invitation, user.getUsername());
            invitationDTOList.add(invitationDTO);
        }

        return invitationDTOList;
    }
    public int deleteInvitation(Integer id) {
        int status = 0;
        // 现在要删除帖子id，由于数据库没有设计级联删除，在高级语言这里实现
        // 1. 先删除评论，2. 删除收藏表，3. 删除帖子
        try {
            personCenterMapper.deleteInvitationComment(id);
            personCenterMapper.deleteCollectionInvitation(id);
            personCenterMapper.deleteInvitationById(id);
        } catch (Exception e) {
            status = -1;
        }
        return status;
    }
}
